require "charwidth"

class Movie
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::TaggableOn

  field :title, :type => String
  field :title_py, :type => String
  field :title_en, :type => String
  field :summary, :type => String
  field :year, :type => Integer, :default => 0
  field :release_date, :type => Date # Time.Time.strptime("20/10/2011", "%d/%m/%Y")
  #评分
  field :average, :type => Float, :default => 0.0
  #星级
  field :stars, :type => Integer, :default => 0
  #多少人参与评价
  field :ratings, :type => Integer, :default => 0
  #排名
  field :score, :type => Float, :default => 0.0

  field :verified, :type => Boolean, :default => false
  field :photo, :type => String
  field :type, :type => String, :default => 'movie'#movie,series
  field :episodes, :type => Integer, :default => 1
  field :minutes, :type => Integer, :default => 0
  field :imdb, :type => String
  field :source_id, :type => String
  field :source, :type => String, :default => 'douban'
  field :season, :type => Integer, :default => 1

  # 别名
  taggable_on :aliases
  # 导演
  taggable_on :directors
  # 主演
  taggable_on :actors
  # 类型
  taggable_on :categories
  # 国家
  taggable_on :countries
  # 语言
  taggable_on :languages

  mount_uploader :photo, MovieUploader

  #index({ :imdb => 1}, { :unique => true,:background=>true })
  index :imdb => 1
  index({ :source_id => 1,:source => 1}, { :unique => true,:background=>true })
  index :score => 1
  index :verified => 1
  index :type => 1
  index :year => 1
  index :title => 1
  index :title_py => 1
  index :title_en => 1
  index :release_date => 1

  validates :source_id, uniqueness: { scope: :source}
  #validates :imdb, uniqueness: true

  has_many :attaches

  #当影片保存时候需要对这些进行验证
  before_save :retotal_score
  before_save :build_title_py
  #当影片创建后需要将影片的导演,演员,类别,语言....保存到其他表里面去
  after_create :build_tag

  attr_accessor :photo_remote_url

  scope :recent_upload, -> { desc(:created_at) }
  scope :newest, -> { desc(:year,:release_date) }
  scope :high_rank, -> { desc(:score) }
  #scope :verified, -> { where(:verified => false,:photo.ne => nil ) }
  scope :verified, -> { where(:photo.ne => nil ) }
  scope :tv, -> { where(:type => 'tv') }
  scope :movie, -> { where(:type => 'movie') }

  before_validation do
    @countries = self.countries
    self.countries = Movie.chinese(@countries)
    self.photo = Movie.download_file(self.photo_remote_url) if !self.photo_remote_url.blank?


  end



  #全文搜索
  include Sunspot::Mongoid
  searchable do
    text :title,:title_py,:title_en
    boolean :verified
    string :categories, :multiple => true
    string :countries, :multiple => true
    string :directors, :multiple => true
    string :actors, :multiple => true
    string :languages, :multiple => true
    integer :year
  end



  #下载图片
  def self.download_file(url)
    img = nil
    begin
      img = MiniMagick::Image.read(open(url).read)
      img.format "jpg"
    rescue => e
      Rails.logger.error { "Movie.download_file ERROR: #{url} #{e}" }
    end
    return img
  end

  def self.chinese(countries)
    countries_new = []
    countries.each do |country|
      if country.include?("中国大陆") or country.include?("大陆")
        countries_new << '中国'
      else
        countries_new << country
      end
    end
    countries_new.uniq
  end

  protected




  #当影片创建后需要将影片的导演,演员,类别,语言....保存到其他表里面去
  def build_tag
    #导演
    unless self.directors.blank?
      @directors = self.directors
      #如果里面有数据
      @directors.each do |director|
        @director = Director.find_or_create_by(:name => director)
        if @director
          @director.update(:number => @director.number+1)
        end
      end
    end

    #演员
    unless self.actors.blank?
      @actors = self.actors
      #如果里面有数据
      @actors.each do |actor|
        @actor = Actor.find_or_create_by(:name => actor)
        if @actor
          @actor.update(:number => @actor.number+1)
        end
      end
    end

    #语言
    unless self.languages.blank?
      @languages = self.languages
      #如果里面有数据
      @languages.each do |language|
        @language = Language.find_or_create_by(:name => language)
        if @language
          @language.update(:number => @language.number+1)
        end
      end
    end

    #国家地区
    unless self.countries.blank?
      @countries = self.countries
      #如果里面有数据
      @countries.each do |country|
        @country = Country.find_or_create_by(:name => country)
        if @country
          @country.update(:number => @country.number+1)
        end
      end
    end

    #类型
    unless self.categories.blank?
      @categories = self.categories
      #如果里面有数据
      @categories.each do |category|
        @category = Category.find_or_create_by(:name => category)
        if @category
          @category.update(:number => @category.number+1)
        end
      end
    end

  end

  #将汉字转换成拼音
  def build_title_py
    #如果已经填写了影片的拼音,就可以不用去生成这个
    return self.title_py unless self.title_py.blank?
    #将全角转换成半角
    title = Charwidth.normalize(self.title)
    title_py = PinYin.abbr(title)
    self.title_py = title_py.downcase
  end

  def retotal_score
    # http://www.douban.com/group/topic/2426734/
=begin
(WR) = (v ÷ (v+m)) × R + (m ÷ (v+m)) × C

R = 该电影的平均分

v = 该电影的总投票数

m = 列入前250所需要的最少票数(目前是20000票)

C = 数据库中所有电影的总平均分(目前是6.7)



=end

    lv = self.ratings || 0.00
    lr = self.average || 0.00
    lc = 6.7
    lm = 25000.00
    self.score = (lv/(lv+lm))*lr+(lm/(lv+lm))*lc
  end

end
